package com.jboost.modules.app.util;

import com.google.common.collect.Maps;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
@Slf4j
public final class Hmacer {
    private static final Integer MAX_AGE_OFFSET = -10;
    private static final Integer MAX_AGE = 300;
    private static final String ALGORITHM = "HmacSHA1";
    public static final String SIGNATURE_KEY = "_signature_";
    public static final String TIMESTAMP_KEY = "_timestamp_";

    public Hmacer() {
    }

    public static String getTimestamp() {
        return String.valueOf((new Date()).getTime() / 1000L);
    }

    public static Map<String, String> convertRequest(Map<String, String[]> stringMap) {
        Map<String, String> params = Maps.newHashMap();
        Iterator i$ = stringMap.keySet().iterator();

        while(i$.hasNext()) {
            String key = (String)i$.next();
            String[] values = (String[])stringMap.get(key);
            if (values != null && values.length > 0) {
                params.put(key, values[0]);
            }
        }

        return params;
    }

    public static String signRequest(String secretKey, Map<String, String> params) {
        try {
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
            mac.init(keySpec);
            mac.update(sortParam(params).getBytes());
            byte[] encryptedBytes = mac.doFinal();
            return Base64.encodeBase64URLSafeString(encryptedBytes);
        } catch (Exception var5) {
            log.error("无法对请求签名");
            return null;
        }
    }

    public static String sortParam(Map<String, String> params) {
        List<String> sortedParams = new ArrayList();
        Iterator i$ = params.keySet().iterator();

        while(i$.hasNext()) {
            String key = (String)i$.next();
            sortedParams.add(key.toLowerCase() + "=" + (String)params.get(key));
        }

        Collections.sort(sortedParams);
        String sortedUrl = null;
        boolean first = true;
        Iterator it = sortedParams.iterator();

        while(it.hasNext()) {
            String param = (String)i$.next();
            if (first) {
                sortedUrl = param;
                first = false;
            } else {
                sortedUrl = sortedUrl + "&" + param;
            }
        }

        return sortedUrl;
    }

    public static boolean authenticate(String secretKey, Map<String, String> params) {
        String signature = (String)params.get("_signature_");
        params.remove("_signature_");
        if (StringUtils.isBlank(signature)) {
            log.warn("参数中没有找到签名或签名为空");
            return false;
        } else {
            long timestamp;
            try {
                timestamp = Long.parseLong((String)params.get("_timestamp_"));
            } catch (NumberFormatException var7) {
                log.warn("时间戳格式错误");
                return false;
            }

            if (timestamp <= 0L) {
                log.warn("参数中没有找到时间戳或者时间戳为小于0");
                return false;
            } else {
                long reqAge = (new Date()).getTime() / 1000L - timestamp;
                if (reqAge < (long)MAX_AGE_OFFSET) {
                    log.warn("时间戳超出允许的范围");
                    return false;
                } else if (reqAge > (long)MAX_AGE) {
                    log.warn("签名已过期");
                    return false;
                } else {
                    return signature.equals(signRequest(secretKey, params));
                }
            }
        }
    }

    public static String generateSecretKey() {
        try {
            KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
            SecretKey key = generator.generateKey();
            return Base64.encodeBase64URLSafeString(key.getEncoded());
        } catch (NoSuchAlgorithmException var2) {
            log.warn("生成SecretKey出现异常", var2);
            return null;
        }
    }
}